var middle=httpVar.substring(httpVar.indexOf('/'));
// bind body event DOMNodeInserted DOMSubtreeModified
document.addEventListener('DOMNodeInserted', function (e) {
    // innerHTML read content
    console.log("插入的节点:", e.target, e.target.tagName);
    com.begin(e.target);
});
// document.addEventListener('DOMNodeInserted', function (e) {
//     // innerHTML read content
//     console.log("修改的节点:", e.target, e.target.tagName);
//     com.begin(e.target);
// });
var com = new Object();
com.getFilterList = function () {
    // return lower token
    return [
        { "img": "src" }, 
        { "a": "href" }, 
        { "div": "data-src" },
        { "script": "src" },
        { "span":"data-src"},
        {"link":"href"}
    ];
};
// backup tag:
// { "include-fragment": "src" },
// { "img": "data-src" },//死循环原因
// { "area": "href" }, 
// { "iframe": "src" }, 

com.begin = function (x) {
    // 1.先替换自己
    this.replaceUrl(x);
    // 2.判断是否有孩子,有我就继续处理
    var childs ;
    try{
        childs = x.childNodes;
    }catch(err){
        return;
    }
    // console.log("长度:", childs.length);
    if (childs.length == 0) {
        return;
    } else {
        for (var i = 0, len = childs.length; i < len; i++) {
            // console.log("长度里面:", i, childs[i]);
            if (childs[i].childNodes.length == 0) {
                com.replaceUrl(childs[i]);
            } else {
                com.begin(childs[i]);
            }
        }
    }
};
com.getDomainFromLink = function(url){
    if (!url){  // if null
        return {domain:'',ok:false};
    }
    begin=url.indexOf('//');
    if (begin<0){
        return {domain:'',ok:false};
    }
    right=url.substr(begin+2);
    end=right.indexOf('/');
    host='';
    if (end<0){ //没有path
        host=right;
    }else{
        host=right.substring(0,end);
    }
    return {domain:host,ok:true};
};
com.match = function(url){
    if (thaisList.length==0){
        return false;
    }
    obj=com.getDomainFromLink(url);
    if (!obj.ok){
        return false;
    }
    domain=obj.domain;
    for (i=0;i<thaisList.length;i++){
        ele=thaisList[i];
        console.log('WhiteList in:',ele);
        if (ele=="*"){
            return true;
        }
        // 1.ip段规则
        if (ele.search('-->')!=-1){ 
            ips=ele.split('-->');
            if (ips.length<2){
                continue;
            }
            ip1=ipToNumber(ips[0].trim());
            ip2=ipToNumber(ips[1].trim());
            ipx=ipToNumber(domain.trim());
            return (ipx>=ip1) && (ipx<=ip2);
        }else{
        // 2.直接规则
            var regx=new RegExp(ele);
            if (regx.test(domain)){
                return true;
            }else{  //3.通配符
                regx=new('^'+ele+'$')
                if (regx.test(domain)){
                    return true;
                }
            }
        }
    }
    return false;
};
// match handle
function matchHanler(host,reg){
   
}
// ip段处理函数
function ipToNumber(ip) {   
	var num = 0;
	if(ip == "") {
		return num;
	}    
    var aNum = ip.split("."); 
    if(aNum.length != 4) {
    	return num;
    }   
    num += parseInt(aNum[0]) << 24;
    num += parseInt(aNum[1]) << 16;
    num += parseInt(aNum[2]) << 8;
    num += parseInt(aNum[3]) << 0;
    num = num >>> 0;//这个很关键，不然可能会出现负数的情况
    return num;  
}    
  
function numberToIp(number) {    
    var ip = "";
    if(number <= 0) {
    	return ip;
    }
    var ip3 = (number << 0 ) >>> 24;
    var ip2 = (number << 8 ) >>> 24;
    var ip1 = (number << 16) >>> 24;
    var ip0 = (number << 24) >>> 24
    
    ip += ip3 + "." + ip2 + "." + ip1 + "." + ip0;
    
    return ip;   
}
com.replaceUrl = function (childNode) {
    myList = this.getFilterList();
    var name;
    try {
        name = childNode.tagName;
    } catch (err) {
        return;
    }

    for (i = 0; i < myList.length; i++) {
        ele = myList[i];
        for (k in ele) {
            if (this.toLower(name) == k) {
                // console.log("Node --> :",ele[k],childNode,childNode.getAttribute(ele[k]));
                oldVal = childNode.getAttribute(ele[k]);
                childNode.setAttribute(ele[k], this.fuck(oldVal, httpVar, httpsVar));
            }
        }
    }
};
com.toLower = function (str) {
    if (!str){
        return ;
    }
    return str.toLowerCase();
};
com.errorToken = '******';
com.fuck = function (url,fuckUrl,fuckUrl2){
    console.log("In ----> :", url);
    // if (!com.match(url)){
    //     console.log("Out <---- :",com.errorToken);   
    //     return com.errorToken;     
    // }
    retUrl = com.fucking(url,fuckUrl,fuckUrl2);
    console.log("Out <---- :",retUrl);
    return retUrl;
}
com.fucking = function (url, fuckUrl, fuckUrl2) {
    if (!url || url.length < 4) {
        return url;
    }
    finalUrl=fuckUrl;
    thisSchem="http";
    thisLocation=document.location.toString();
    if (thisLocation!="" && thisLocation.substring(0,5)=='https'){
        finalUrl=fuckUrl2;
        thisSchem="https";
    }
    if (url.search(proxyHost)!=-1){
        return url; //有这个域说明处理了
    }else{  //如果没有域，再判断是否有middle 
        if (url.search(middle)!=-1){
            finalHost=finalUrl.substring(0,finalUrl.indexOf('/'));
            return thisSchem+'://'+finalHost+url;
        }
    }
    f4 = url.substring(0, 4);
    f1 = url.substring(0, 1);
    f2 = url.substring(0, 2);
    fn2 = url.substring(1, 2);
    
    if ((f4 == "http") || (f2 == "ws")) {
        strs = url.split('//');
        strLen = strs.length;
        if (strLen > 1) {
            retStr = strs[0].concat('//')
            if (strs[0] == "https:") {
                retStr = retStr.concat(fuckUrl2);
            } else {
                retStr = retStr.concat(fuckUrl);
            }
            for (i = 1; i < strLen; i++) {
                retStr = retStr.concat(strs[i]);
            }
        }
        return retStr;
    } else if ((f1 == '/') && (fn2 != '/')) {
        retStr = '/'.concat(reqHost).concat('/').concat(url.substring(1));
        return retStr;
    } else if (f2 == '//') {
        retStr = '//'.concat(finalUrl).concat('/').concat(url.substring(2));
        return retStr;
    } else {
        return url;
    }
};